package library.core.user;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import library.database.user.DatabaseAdminProxy;
import library.database.user.DatabaseReaderProxy;
import library.database.user.DatabaseUserProxy;
import library.utils.Info;

public class User {

	private String name;
	private int id;
	private String email;
	private String department;
	
	public User() {
	}
	/**
	 * 修改密码
	 * @param oldp
	 * @param newp
	 * @return
	 */
	public Info modifyPassword(String oldp, String newp){
		try {
			DatabaseReaderProxy proxy = new DatabaseReaderProxy();
			ResultSet rs = proxy.seek(this.id);
			String paswr = null;
			while(rs.next()){
				paswr = rs.getString("password");
				if (!paswr.equals(oldp) || paswr==null || oldp.length() == 0) {
					return new Info("原始密码错误！");
				}
			}
			if(newp.length()>225)
				return new Info("密码过长！");
			else if (newp.length()==0)
				return new Info("未输入新密码！");
			proxy.modify(2,newp,this.id);
			return Info.success("");
		} catch (SQLException |ClassNotFoundException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new Info("系统错误！");
		}

	}
	/**
	 * 修改信息
	 * @param name
	 * @param email
	 * @param department
	 * @return
	 */
	public Info modifyInfo(String name, String email, String department) {
		try {
			boolean flag = isReader();
			this.name = name;
			this.email = email;
			this.department = department;
			DatabaseUserProxy proxy = new DatabaseUserProxy();
			if(!flag)
				proxy = new DatabaseAdminProxy();
			else
				proxy = new DatabaseReaderProxy();
			if(name.length()>255)
				return new Info("用户名过长！");
			proxy.modify(1, name, this.id);
			proxy.modify(3,email,this.id);
			proxy.modify(4,department,this.id);
			return Info.success("");
		} catch (SQLException |ClassNotFoundException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new Info("系统错误！");
		}
	}
	
	public String descDepartment() {
		return isAdmin() ? "部门" : "学院";
	}
	
	/**
	 * 是否为读者
	 * @return 返回是否为读者
	 * @throws SQLException
	 */
	public boolean isReader() {
		return this instanceof Reader;
	}
	
	/**
	 * 是否为管理员
	 * @return 返回是否为管理员
	 */
	public boolean isAdmin() {
		return this instanceof Admin;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getDepartment() {
		return department;
	}
	public void setDepartment(String department) {
		this.department = department;
	}
	
}
